<?php
require_once 'app/bootstrap.php';

$dbSection              = new Model_Resource_SiteResource_Section();
$dbPhone                = new Model_Resource_Phone();
$dbPhoneRelation        = new Model_Resource_Phone_Phone();
$dbAdvert               = new Model_Resource_SiteResource_Section_Advert();
$dbPhoneAdvertRelation  = new Model_Resource_Phone_Advert();

$helper = new Helper_CurrentDate;
$date = $helper->getCurrentDate();

if (date('D', strtotime($date)) == 'Sun') {
    echo _('No read ads at Sunday. Have a nice weekend! ;)');
    exit();
}


$sections = $dbSection->fetchAll('resource_id = 1 AND (last_read_at < "' . $date . '" OR last_read_at IS NULL)');

$reader = new Rent_Reader_Premier();

if ($sections->count()) {
    /**
     * Set path to archive
     */
    $reader->setArchivePath(Helper_Advert::getArchivePath(
        $sections->current()->resource_id),
        $helper->getCurrentYear(),
        $helper->getCurrentMonth()
    );
    /**
     * Set archive file format
     */
    $reader->setHashNameFormat(Helper_Advert::getHashNameFormat($helper->getCurrentDay()));
    /**
     * Set current date
     */
    $reader->setCurrentDate($date);
}

$newPhones = 0;
$totalAdverts = 0;

$sectionsAds = array();
$phoneRows = array();
$phoneRelations = array();
$existPhoneRelations = array();
$hashedAdverts = array();
$return = '';
try {
    /** @var $section Zend_Db_Table_Row */
    foreach ($sections as $section) {
        $sectionId = $section->id;
        $url = $section->section_url;
        $reader->setUrl($url);
        $reader->setSectionId($sectionId);

        $sectionsAds[$sectionId]['adverts'] = $adverts = $reader->getAds();

        $dbSection->getAdapter()->beginTransaction();

        //update last read date in the section
        $section->last_read_at = $date;
        $section->save();

        if (! $adverts) {
            continue;
        }

        //save to archive
        if (!$reader->hasArchive()) {
            $reader->saveToArchive();
        }

        $sectionsAds[$sectionId] = $section->toArray();

        $totalAdverts += count($adverts);
        foreach ($adverts as $advert) {
            $advertPhonesIds = array();

            //set phones
            foreach ($advert['phones'] as $phone) {
                $escapePhone = ltrim($phone, 0);
                if (empty($phoneRows[$phone])) {
                    $row = $dbPhone->fetchRowByPhone($escapePhone);
                } else {
                    $row = $phoneRows[$phone];
                }
                if (null === $row) {
                    $row = $dbPhone->createRow(array(
                        'count_advert'  => 1,
                        'phone'         => $escapePhone,
                        'created_at'    => $date,
                        'last_found_at' => $date,
                    ));
                    $phoneRows[$phone] = $row;
                    $newPhones++;
                } else {
                    $row->count_advert++;
                    $row->last_found_at = $date;
                }
                $row->save();
                $advertPhonesIds[$row->id] = $row->id;
            }

            //set phone-phone relations
            if (count($advertPhonesIds) > 1) {
                foreach ($advertPhonesIds as $selfId) {
                    foreach ($advertPhonesIds as $id) {
                        if ($id == $selfId || !empty($phoneRelations["$selfId,$id"])) {
                            continue;
                        }
                        $phoneRelations["$selfId,$id"] = $advertPhonesIds;
                    }
                }
            }

            try {
                $hash = $advert['hash'];
                if (! isset($hashedAdverts[$hash])) {
                    $rowAdvert = $dbAdvert->createRow(array(
                        'advert'        => $advert['content'],
                        'hash'          => $hash,
                        'created_at'    => $date,
                        'section_id'    => $sectionId,
                    ));
                    $advertId = $rowAdvert->save();
                    $advertDuplicated = false;
                } else {
                    $advertDuplicated = true;
                }
            } catch (Zend_Db_Exception $e) {
                if (strpos($e->getMessage(), '1062 Duplicate') === false) {
                    throw $e;
                }
                $advertDuplicated = true;
            }
            if ($advertDuplicated) {
                if (! isset($hashedAdverts[$hash])) {
                    $rowAdvert = $dbAdvert->fetchRow("hash = '$hash'");
                } else {
                    $rowAdvert = $hashedAdverts[$hash];
                }
                $advertId = $rowAdvert->id;
                $rowAdvert->count_repeat++;
                $rowAdvert->last_repeat_at = $date;
                $hashedAdverts[$hash] = $rowAdvert;
            }

            //set phone-advert relation
            foreach ($advertPhonesIds as $phoneId) {
                try {
                    $dbPhoneAdvertRelation->createRow(array(
                        'phone_id'  => $phoneId,
                        'advert_id' => $advertId,
                    ))->save();
                } catch (Zend_Db_Exception $e) {
                    if (strpos($e->getMessage(), '1062 Duplicate') === false) {
                        throw $e;
                    }
                }
            }
        }
        //save phone-phone relations
        foreach ($phoneRelations as $advertPhonesIds) {
            foreach ($advertPhonesIds as $selfId) {
                foreach ($advertPhonesIds as $id) {
                    if ($id == $selfId || !empty($existPhoneRelations["$selfId,$id"])) {
                        continue;
                    }
                    $rowSet = $dbPhoneRelation->find($selfId, $id);
                    if (0 == $rowSet->count()) {
                        $data = array(
                            'phone_id'         => $selfId,
                            'related_phone_id' => $id,
                        );
                        $row = $dbPhoneRelation->createRow($data);
                        $row->save();
                    }
                    $existPhoneRelations["$selfId,$id"] = $advertPhonesIds;
                }
            }
        }

        //save hashed adverts
        foreach ($hashedAdverts as $row) {
            $row->save();
        }

        $dbSection->getAdapter()->commit();
    }
} catch (Exception $e) {
    $return .= $e->getMessage() . PHP_EOL;
    $return .= $e->getTraceAsString() . PHP_EOL;
}
$cntDuplicatedAdverts = count($hashedAdverts);
$return .= _('Total adverts') . ": $totalAdverts" . PHP_EOL;
$return .= _('Added new phones') . ": $newPhones" . PHP_EOL;
$return .= _('Duplicated') . ": $cntDuplicatedAdverts" . PHP_EOL;
echo $return;

@mail('andkirby@gmail.com', 'Adverts get', date('Y-m-d') . PHP_EOL . $return);
